import {
  exportExcelApi,
  getChannelLog,
  getProgramOptions,
} from '@/services/api';
import { removeEmptyValues } from '@/utils';
import { FileSearchOutlined } from '@ant-design/icons';
import type { ActionType } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { useLocation } from '@umijs/max';
import { useRequest } from 'ahooks';
import { Button, Tag, message } from 'antd';
import { useMemo, useRef } from 'react';

const Journal: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const formRef = useRef<any>();

  // 查询所有商户
  const { data: merchantList } = useRequest(async () => {
    return await getProgramOptions();
  });

  // 获取path值
  let location = useLocation();

  const { loading, runAsync } = useRequest(
    async (_parames) => {
      return await exportExcelApi({
        ..._parames,
      });
    },
    {
      manual: true,
    },
  );

  const _text = useMemo(() => {
    if (location.pathname === '/journal/channelLog') {
      return '转换的号码';
    } else if (location.pathname === '/journal/overdueLog') {
      return '逾期号码';
    } else if (location.pathname === '/journal/bindingLog') {
      return '绑定号码';
    } else if (location.pathname === '/journal/unbindLog') {
      return '解绑号码';
    } else {
      return '手机号';
    }
  }, [location]);

  const columns: any = [
    {
      title: '商户',
      dataIndex: 'user__name',
      valueType: 'select',
      render: (text: string, record: any) => {
        return (
          <div>
            {record?.user?.id} - {record?.user?.name}
          </div>
        );
      },
      fieldProps: {
        onChange: (value) => {
          formRef?.current?.submit();
        },
        options:
          merchantList?.data?.map((e) => {
            return {
              label: e?.label,
              value: e?.label,
            };
          }) ?? [],
        showSearch: true,
      },
    },
    {
      title: '时间',
      dataIndex: 'create_time__range',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            create_time__range: [
              `${value?.[0]} 00:00:00`,
              `${value[1]} 23:59:59`,
            ],
          };
        },
      },
      fieldProps: {
        onChange: (value) => {
          formRef?.current?.submit();
        },
      },
    },

    {
      title: _text,
      dataIndex: 'mobile',
      hideInTable: location.pathname === '/journal/batterySearch' ||location.pathname === '/journal/openLog' ,
      hideInSearch: location.pathname === '/journal/batterySearch' || location.pathname === '/journal/openLog'
    },
    {
      title: '查询的电池',
      dataIndex: 'content',
      hideInTable: location.pathname !== '/journal/batterySearch',
      hideInSearch: location.pathname !== '/journal/batterySearch',
    },
    {
      title: '电柜编号',
      dataIndex: 'content',
      hideInTable: location.pathname !== '/journal/openLog',
      hideInSearch: true,
      // hideInSearch: location.pathname !== '/journal/openLog',
      render: (text, record) => {
      /* 只展示-前面的字符 */
      return text?.split('-')[0];
      },
    },
    {
      title: '仓门',
      dataIndex: 'test',
      hideInTable: location.pathname !== '/journal/openLog',
      hideInSearch: true,
      // hideInSearch: location.pathname !== '/journal/openLog',
      render: (text, record) => {
      /* 只展示-前面的字符 */
      return record?.content?.split('-')[1];
      },
    },
    {
      title: '电柜编号',
      dataIndex: 'content__contains',
      hideInTable: true,
      hideInSearch: location.pathname !== '/journal/openLog',
    },
    {
      title: '绑定的电池编码',
      dataIndex: 'content',
      //  隐藏
      hideInTable: location.pathname !== '/journal/bindingLog',
      hideInSearch: location.pathname !== '/journal/bindingLog',
    },
    {
      title: '解绑的电池编码',
      dataIndex: 'content',
      //  隐藏
      hideInTable: location.pathname !== '/journal/unbindLog',
      hideInSearch: location.pathname !== '/journal/unbindLog',
    },
    // {
    //   title: '券名称',
    //   dataIndex: ['code', 'title'],
    //   hideInSearch: true,
    //   render: (text, record) => {
    //     return (
    //       <>
    //         {' '}
    //         <Tag bordered={false} color="purple">
    //           {record?.code?.code}
    //         </Tag>{' '}
    //         {record?.code?.title}{' '}
    //       </>
    //     );
    //   },
    // },
    {
      title: '时间',
      dataIndex: 'create_time',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status_text',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <Tag
            color={record?.status === 1 ? 'success' : 'error'}
            bordered={false}
          >
            {record?.status_text}
          </Tag>
        );
      },
    },
    {
      disable: true,
      title: '状态',
      dataIndex: 'status',
      filters: true,
      onFilter: true,
      ellipsis: true,
      valueType: 'select',
      hideInTable: true,
      valueEnum: {
        1: {
          text: '成功',
        },
        2: {
          text: '失败',
        },
      },
      fieldProps: {
        onSelect: (value) => {
          formRef?.current?.submit();
        },
      },
    },
  ];

  return (
    <>
      <ProTable
        bordered
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={async (_parame) => {
          const { pageSize, current, ...ret } = _parame;

          let _params: any = {};
          switch (location.pathname) {
            case '/journal/channelLog':
              _params.type = 'channel';
              break;
            case '/journal/overdueLog':
              _params.type = 'overdue';
              break;
            case '/journal/bindingLog':
              _params.type = 'binding';
              break;
            case '/journal/unbindLog':
              _params.type = 'unbind';
              break;
            case '/journal/batterySearch':
              _params.type = 'querybet';
              break;
            case '/journal/openLog':
              _params.type = 'rear';
              break;
            default:
              break;
          }

          const { data } = await getChannelLog({
            page: current,
            size: pageSize,
            filters: JSON.stringify({
              ...removeEmptyValues({ ...ret, ..._params }),
            }),
          });
          return {
            data: data?.list ?? [],
            success: true,
            total: data?.count,
          };
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{
          defaultPageSize: 10,
        }}
        dateFormatter="string"
        formRef={formRef}
        toolBarRender={() => [
          ( !['/journal/batterySearch','/journal/openLog'].includes(location.pathname) ) && (
            <Button
              key="button"
              icon={<FileSearchOutlined />}
              onClick={async () => {
                let _faileName: string = '';
                let _header: any = ['ID', '手机号', '电池', '创建时间'];
                let _type: string = 'channel';
                let _fields: any = [];
                if (location.pathname === '/journal/channelLog') {
                  _faileName = '渠道转个人日志';
                  _header = ['商户', '转换的号码', '时间', '状态'];
                  _type = 'channel';
                  _fields = [
                    'mp_users.user_id.name',
                    'mobile',
                    'create_time',
                    'status',
                  ];
                } else if (location.pathname === '/journal/overdueLog') {
                  _faileName = '消除逾期日志';
                  _header = ['商户', '逾期号码', '时间', '状态'];
                  _type = 'overdue';
                  _fields = [
                    'mp_users.user_id.name',
                    'mobile',
                    'create_time',
                    'status',
                  ];
                } else if (location.pathname === '/journal/bindingLog') {
                  _faileName = '绑定电池日志';
                  _header = [
                    '商户',
                    '绑定号码',
                    '绑定的电池编码',
                    '时间',
                    '状态',
                  ];
                  _type = 'binding';
                  _fields = [
                    'mp_users.user_id.name',
                    'mobile',
                    'content',
                    'create_time',
                    'status',
                  ];
                } else if (location.pathname === '/journal/unbindLog') {
                  _faileName = '解绑电池日志';
                  _header = [
                    '商户',
                    '解绑号码',
                    '解绑的电池编码',
                    '时间',
                    '状态',
                  ];
                  _fields = [
                    'mp_users.user_id.name',
                    'mobile',
                    'content',
                    'create_time',
                    'status',
                  ];
                  _type = 'unbind';
                }

                try {
                  await runAsync({
                    filename: _faileName,
                    header: _header,
                    fields: _fields,
                    table: 'journal_alllog',
                    where: `type='${_type}'`,
                  });

                  message.success(`文件${_faileName}导出成功`);
                } catch (error) {}
              }}
              type="primary"
              loading={loading}
            >
              导出
            </Button>
          ),
        ]}
      />
    </>
  );
};

export default Journal;
